package com.example.administrator.nurse.present;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.administrator.nurse.OnPatientGetDataListener;
import com.example.administrator.nurse.R;
import com.example.administrator.nurse.base.BaseActivity;
import com.example.administrator.nurse.base.BaseFragment;
import com.example.administrator.nurse.common;
import com.example.administrator.nurse.fragment.PatientAtOutFragment;
import com.example.administrator.nurse.fragment.PatientAtRoomFragment;
import com.example.administrator.nurse.fragment.PatientRoomFragment;
import com.example.administrator.nurse.model.bean.PatientRoomBean;
import com.example.administrator.nurse.widget.LoginInputEdit;
import com.example.administrator.nurse.widget.SearchInput;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 *  Created by 林锦丰 on 2016/4/24.
 *
 *  完善 by 林冠宏
 *  1.该页面所附带的 3 个 fragment 使用到的数据是公共的，所以直接在这里定义所有的
 *
 *  2.数据传输主要通过接口回调
 *
 *  3.目的是为了解耦和减少不必要的重复代码
 *
 */

public class PatientRoomActivity extends BaseActivity {

    private static int Flag = 0; // 标志位，标记当前操作数据的 fragment
    private List<BaseFragment> fragmentList;
    public static List<PatientRoomBean> list = new ArrayList<>(); // 公共数据源
    public static final int GetDataNormal = 0x11;
    public static final int GetDataMore   = 0x12;
    public static final int OnSaveCallBack = 0x13;
    private View selectTmp;
    private String[] flag;
    private int currentIndex=0;
    public static OnPatientGetDataListener PatientGetDataListener;
    private View typeHead,typeLine,typeSearch;
    PatientRoomFragment patientRoomFragment;// 按病房
    PatientAtRoomFragment patientAtRoomFragment;
    PatientAtOutFragment patientAtOutFragment; // 出院病人

    @Override
    protected int setLayotId() {
        return R.layout.patient_room_activity;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        /** fragment 获取数据的接口实例化 */
        PatientGetDataListener = new OnPatientGetDataListener() {
            @Override
            public void onGetData(boolean isLoadMore) {
                /** 从 fragment 里面回调，肯定 不是搜索 */
                getData(isLoadMore, null);
            }
        };
        // 第一次加载数据，不能在这里加载，迁移到 fragment 加载
        //getData(false,null);
    }

    /** 子类 fragment 用来处理 数据回调的接口 */
    public interface OnDealWithDataListener{
        void onSuccessDealWith(int requestCode, Object object, String response);
        void onFailureDealWith(int requestCode, Object object, String response);
    }

    @Override
    protected void onFailure(int requestCode, Object object, String errorMsg) {
        stopLoadingDialog();

    }

    @Override
    protected void onSuccess(int requestCode, Object object, String response) {
        stopLoadingDialog();
        switch(Flag){
            case 0:  // 按病房
                patientRoomFragment  .onSuccessDealWith(requestCode, object, response);
                break;
            case 1:  // 按病人
                patientAtRoomFragment.onSuccessDealWith(requestCode,object,response);
                break;
            case 2:  // 按出院病人
                patientAtOutFragment .onSuccessDealWith(requestCode, object, response);
                break;
        }
    }

    private static int lid = 0;
    public void getData(boolean loadMore,String isSearch){
        startLoadingDialog();
        RequestParams requestParams = new RequestParams();
        requestParams.put("status",StatusSelect);
        requestParams.put("id", common.nId); // 护士 id
        requestParams.put("level",LevelSelect);
        if(isSearch!=null){
            requestParams.put("con",isSearch);
        }else{
            SearchInput.searchInput.setText("");
        }
        List<String> l = new ArrayList<>();
        switch (StatusSelect){
            case -1:l.add("全部");break;
            case 0:l.add("在外出");break;
            case 1:l.add("在病房");break;
            case 2:l.add("家属陪伴外出");break;
            case 3:l.add("外出检查");break;
            case 4:l.add("未记录");break;
        }
        switch (LevelSelect){
            case -1:l.add("全部");break;
            case 0:l.add("特级护理");break;
            case 1:l.add("一级护理");break;
            case 2:l.add("二级护理");break;
            case 3:l.add("三级护理");break;
        }
        if(loadMore){
            requestParams.put("lid",lid); /** 加载更多的 id */
            doPost(GetDataMore, l, common.Host + "/Controller/LghPatrolController.php?func=GetRoomWatchData", requestParams);
        }else {
            doPost(GetDataNormal, l, common.Host + "/Controller/LghPatrolController.php?func=GetRoomWatchData", requestParams);
        }
    }

    public static void dealDataJson(String response,boolean isLoadMore){
        if(response!=null){
            try{
                JSONArray jsonArray = new JSONArray(response);
                int length = jsonArray.length();
                if(length>0 && !isLoadMore){
                    list.clear();
                }
                for(int i=0;i<length;i++){
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    PatientRoomBean bean = new PatientRoomBean();
                    bean.setName(getJSONValue(jsonObject, "name"));

                    bean.setId(getJSONValue(jsonObject, "id"));
                    bean.setAge(getJSONValue(jsonObject, "age"));
                    bean.setSex(getJSONValue(jsonObject, "sex"));
                    bean.setBednum(getJSONValue(jsonObject, "numOfBed"));
                    bean.setState((getJSONINTValue(jsonObject, "status")));

                    // 数据库没有病区号
                    bean.setDMent(getJSONValue(jsonObject, "department"));

                    bean.setAreanum(getJSONValue(jsonObject, "numOfRoom"));
                    bean.setRoomnum(getJSONValue(jsonObject, "numOfRoom"));
                    bean.setContent(getJSONValue(jsonObject, "content"));

                    bean.setDoc(getJSONValue(jsonObject, "doctor"));
                    bean.setLevel(getJSONINTValue(jsonObject, "nurse_grade"));
                    bean.setTime(getJSONValue(jsonObject, "patrolTime"));

                    if(i==length-1){
                        lid = getJSONINTValue(jsonObject, "id");
                    }
                    list.add(bean);
                }
            }catch (Exception e){
                Log.d("zzzzz", e.toString());
            }
        }
    }

    private int StatusSelect = -1;
    private int LevelSelect  = -1;
    public static SearchInput SearchInput;
    private void initView(){
        configCommonHeader(PatientRoomActivity.this, getResources().getString(R.string.patient_room), 0);

        // 配置三个公共
        typeHead   = f(R.id.typeHead);
        typeLine   = f(R.id.typeLine);
        typeSearch = f(R.id.typeSearch);
        /** 现在开始绑定 列表和 搜索的点击事件 */
        SearchInput = new SearchInput(this,getWindow().getDecorView())
                .withTypeMenu(R.menu.patient_state)
                .withSortMenu(R.menu.patient_level)
                /**<item android:id="@+id/out"android:title="在外出"/>
                 <item android:id="@id/room"android:title="在病房"/>
                 <item android:id="@+id/out_family"android:title="家属陪伴外出"/>
                 <item android:id="@+id/outcheck"android:title="外出检查"/>
                 <item android:id="@+id/not_recode"android:title="未记录"/>*/
                .withMenuItemClickListener(new SearchInput.OnMenuItemClickListener() {
                    @Override
                    public void menuTypeItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.out:
                                StatusSelect = 0;
                                break;
                            case R.id.room:
                                StatusSelect = 1;
                                break;
                            case R.id.out_family:
                                StatusSelect = 2;
                                break;
                            case R.id.outcheck:
                                StatusSelect = 3;
                                break;
                            case R.id.not_recode:
                                StatusSelect = 4;
                                break;
                            case R.id.all:
                                StatusSelect = -1;
                                break;
                        }
                        getData(false,null);
                    }

                    @Override
                    public void menuSortItemClick(MenuItem item) {
                        /**<item android:id="@+id/first"android:title="特级护理"/>
                         <item android:id="@+id/second"android:title="一级护理"/>
                         <item android:id="@+id/third"android:title="二级护理"/>
                         <item android:id="@+id/fourth"android:title="三级护理"/>*/
                        switch (item.getItemId()) {
                            case R.id.first:
                                LevelSelect = 0;
                                break;
                            case R.id.second:
                                LevelSelect = 1;
                                break;
                            case R.id.third:
                                LevelSelect = 2;
                                break;
                            case R.id.fourth:
                                LevelSelect = 3;
                                break;
                            case R.id.all:
                                LevelSelect = -1;
                                break;
                        }
                        getData(false,null);
                    }
                })
                .withSearchClickListener(new SearchInput.OnSearchClickListener() {
                    @Override
                    public void searchClick(LoginInputEdit searchInput) {
                        getData(false,searchInput.getStringText());
                    }
                })
                .init();
        // 公共结束

        LinearLayout container = (LinearLayout) f(R.id.container);

        View room= LayoutInflater.from(PatientRoomActivity.this).inflate(R.layout.select_item,(ViewGroup)getWindow().getDecorView(),false);
        ((TextView)room.findViewById(R.id.text)).setText("按病房");
        ((TextView)room.findViewById(R.id.text)).setTextColor(getResources().getColor(R.color.navbar));
        selectTmp=room;

        room.findViewById(R.id.line).setVisibility(View.VISIBLE);
        View patient= LayoutInflater.from(PatientRoomActivity.this).inflate(R.layout.select_item,(ViewGroup)getWindow().getDecorView(),false);
        ((TextView)patient.findViewById(R.id.text)).setText("按病人");

        View outpatient= LayoutInflater.from(PatientRoomActivity.this).inflate(R.layout.select_item,(ViewGroup)getWindow().getDecorView(),false);
        ((TextView)outpatient.findViewById(R.id.text)).setText("已出院病人巡视记录");

        container.addView(room);
        container.addView(patient);
        container.addView(outpatient);

        onItemListener(room, patient, outpatient);

        // 下面开始配置 fragment，注意并不是，一次性全部实例化，下面 commit 的时候才会
        fragmentList=new ArrayList<BaseFragment>();
        patientRoomFragment   = new PatientRoomFragment();// 按病房
        patientAtRoomFragment = new PatientAtRoomFragment();
        patientAtOutFragment  = new PatientAtOutFragment(); // 出院病人

        fragmentList.add(patientRoomFragment);
        fragmentList.add(patientAtRoomFragment);
        fragmentList.add(patientAtOutFragment);
        flag=new String[]{"tag2","tag1","tag3"};

        // 下面 是 首次进入的显示
        changeShowStatus(true,true,false) ;
        getSupportFragmentManager().beginTransaction()
                .add(R.id.patient_container, patientRoomFragment, flag[0]).commit();
    }

    /** 切换页面时不需要重新加载，只需要重新匹配，重新匹配的方法是 adapter.notifyDataSetChanged() */
    private void switchFragment(int i){ // 如果从 0 点 1，那么 i = 1 , currentIndex =0
        BaseFragment tofragment   = (BaseFragment) getSupportFragmentManager().findFragmentByTag(flag[i]);
        BaseFragment fromfragment = (BaseFragment) getSupportFragmentManager().findFragmentByTag(flag[currentIndex]);
        replaceFragment(tofragment,fromfragment,i);
//        if (tofragment==null){
//            getSupportFragmentManager().beginTransaction().hide(fromfragment).add(R.id.patient_container, fragmentList.get(i), flag[i]).commit();
//        }else {
//            /** 下面这句不注释会引发一个 罕见的 异常 */
//            //getSupportFragmentManager().beginTransaction().hide(fromfragment).show(tofragment).commit();
//        }
        /** 下面不用再手动调用 adapter.notifyDataSetChanged() 会空指针，因为每个 f 在上面 add 的时候就实例化了*/
        try {
            switch (i) {
                case 0:
                    changeShowStatus(true, true, false);
                    PatientRoomActivity.Flag = 0;
                    //patientRoomFragment.adapter.notifyDataSetChanged();
                    break;// 按病房
                case 1:
                    changeShowStatus(true, true, true);
                    PatientRoomActivity.Flag = 1;
                    //patientAtRoomFragment.adapter.notifyDataSetChanged();
                    break;// 按病人
                case 2:
                    changeShowStatus(false, false, true);
                    Log.d("zzzzz","--------按出院病人");
                    PatientRoomActivity.Flag = 2;
                    //patientAtOutFragment.adapter.notifyDataSetChanged();
                    break;// 按出院病人
            }
        }catch(Exception e){
            Log.d("zzzzz",e.toString());
        }
    }

    /** 统一配置 顶部 view 的显示 */
    private void changeShowStatus(boolean showHead,boolean showLine,boolean showSearch){
        if(showHead)
            typeHead.setVisibility(View.VISIBLE);
        else
            typeHead.setVisibility(View.GONE);
        if(showLine)
            typeLine.setVisibility(View.VISIBLE);
        else
            typeLine.setVisibility(View.GONE);
        if(showSearch)
            typeSearch.setVisibility(View.VISIBLE);
        else
            typeSearch.setVisibility(View.GONE);
    }

    private void replaceFragment(Fragment newFragment,Fragment fromFragment,int i) {

        android.support.v4.app.FragmentTransaction trasection = getSupportFragmentManager().beginTransaction();
        if (newFragment==null){
            getSupportFragmentManager().beginTransaction().hide(fromFragment).add(R.id.patient_container, fragmentList.get(i), flag[i]).commit();
        }else{
            if(!newFragment.isAdded()) {
                try {
                    trasection.replace(R.id.patient_container, newFragment);
                    trasection.addToBackStack(null);
                    trasection.commit();

                } catch (Exception e) {
                    // TODO: handle exception
                    //AppConstants.printLog(e.getMessage());

                }
            }else {
                //.hide(fromFragment)
                trasection.show(newFragment).commit();
            }
        }
    }

    private void onItemListener(final View ... views){
        for (int i=0;i<views.length;i++){
            final View view=views[i];
            final int selectI=i; // 0 , 1 , 2
            views[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (selectTmp!=null){
                        ((TextView)selectTmp.findViewById(R.id.text)).setTextColor(getResources().getColor(R.color.gray));
                        selectTmp.findViewById(R.id.line).setVisibility(View.GONE);
                    }
                    selectTmp=view;
                    ((TextView)view.findViewById(R.id.text)).setTextColor(getResources().getColor(R.color.navbar));
                    view.findViewById(R.id.line).setVisibility(View.VISIBLE);
                    switchFragment(selectI);
                    currentIndex=selectI; //
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("zzzzz", "onActivityResult requestCode "+requestCode);
        if(resultCode==1){
            Log.d("zzzzz","resultCode==1");
            getData(false,null);
        }else{
            Log.d("zzzzz","resultCode!=1");
        }
    }

}
